//
//  ColletionViewController.m
//  记账deam
//
//  Created by apple on 16/5/5.
//  Copyright © 2016年 --- 杨江 ---. All rights reserved.
//

#import "ColletionViewController.h"
#import "ClassCollectionViewCell.h"
#import "HeaderLabelView.h"
#import "YJCalenderView.h"
#import "Changed.h"
#import "AddBuyClassViewController.h"
#define BUTTON_WIDTH (CGRectGetWidth(self.keyBord.bounds) - 5)/4
#define BUTTON_HEIGHT (CGRectGetHeight(self.keyBord.bounds) - 40)/4

@interface ColletionViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>
@property(nonatomic,strong)UICollectionView *classification;
@property(nonatomic,strong)NSMutableDictionary *dataSource;
@property(nonatomic,strong)HeaderLabelView *headerView;
@property(nonatomic,strong)UIView *keyBord;
@property(nonatomic,assign)BOOL flag;
@property(nonatomic,assign)BOOL flag1;
@property(nonatomic,assign)BOOL zeroFlag;
@property(nonatomic,strong)NSMutableString *beforeStr;
@property(nonatomic,strong)NSMutableString *backStr;
@property(nonatomic,strong)YJCalenderView *canlenderView;
@property (nonatomic,assign) BOOL isTaped;
@property(nonatomic,strong)NSMutableDictionary *dic;
@property(nonatomic,strong)NSMutableString *str;
@property(nonatomic,strong)NSMutableString *keyStr;

@end

@implementation ColletionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    self.title = @"记一笔";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"关闭"] style:UIBarButtonItemStylePlain target:self action:@selector(popTheVC)];
    [self initTheDataSource];
        [self.view addSubview:self.classification];
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.keyBord];
    
    [self.view addSubview:self.canlenderView];

    
}

- (void)popTheVC{

    [self.navigationController popViewControllerAnimated:YES];
}

- (void)initTheDataSource{
    _beforeStr = [NSMutableString stringWithFormat:@"0"];
    _backStr = [NSMutableString stringWithFormat:@"00"];
    NSDictionary *dic = @{@"餐饮":@"餐饮4",@"酒水":@"酒水4",@"交通":@"交通4",@"旅游":@"旅游4",@"水电费":@"水电费4",@"购物":@"团购4",@"运动":@"运动健身4",@"游戏娱乐":@"游戏娱乐4",@"添加":@"加号4"
                          
                          
                          };

    _dataSource = [NSMutableDictionary dictionaryWithDictionary:dic];
    [_classification reloadData];
}
#pragma mark -- 计算字符串长度
- (CGSize)getSizeWithMessage:(NSString *)message{
    
    CGSize messageSize = CGSizeZero;
    
    CGRect rect = [message boundingRectWithSize:CGSizeMake(180, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]} context:nil];
    
    messageSize = rect.size;
    
    return messageSize;
}


#pragma mark -- <UICollectionViewDelegate,UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [_dataSource allKeys].count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    ClassCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    NSArray *arr = [NSArray arrayWithArray:[_dataSource allKeys]];
    CGSize measseg = [self getSizeWithMessage:arr[indexPath.row]];
    cell.label.text  = arr[indexPath.row];
    cell.messageSize = measseg;
    [cell.classImage setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@",_dataSource[arr[indexPath.row]]]]];
    cell.label.textColor = [UIColor colorWithRed:0.1682 green:0.0279 blue:0.0657 alpha:1.0];

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ClassCollectionViewCell *cell = (ClassCollectionViewCell *)[self collectionView:collectionView cellForItemAtIndexPath:indexPath];
    NSArray *arr = [NSArray arrayWithArray:[_dataSource allKeys]];
    UIImageView *view = [[UIImageView alloc]initWithFrame:cell.classImage.frame];
    if (indexPath.row == arr.count - 1) {
        AddBuyClassViewController *addbuyVC = [[AddBuyClassViewController alloc]init];
        [self.navigationController pushViewController:addbuyVC animated:YES];
        
    }else{
        _isTaped = YES;
    [view setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@",_dataSource[arr[indexPath.row]]]]];
    view.center = CPM(CGRectGetMidX(cell.frame) + 5, CGRectGetMidY(cell.frame) + 128);
    [self.view addSubview:view];
    [self cellAnimationView:view];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [view removeFromSuperview];
        [_headerView.logoImg setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@",_dataSource[arr[indexPath.row]]]]];
        _isTaped = NO;
        _headerView.messageSize = [self getSizeWithMessage:cell.label.text];
        _headerView.classNameLabel.text = cell.label.text;

    });
    }
}
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _classification) {
         return !_isTaped;
    }
    else return YES;
   
}


#pragma mark --- getter

- (UICollectionView *)classification{

    if (!_classification) {
        UICollectionViewFlowLayout  *layout = [[UICollectionViewFlowLayout alloc] init];
        //滚动方向
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        //设置 item 的尺寸
        layout.itemSize = CGSizeMake(70, 70);
        //item 之间的最小间距
        layout.minimumInteritemSpacing = 5;
        //item 每一行之间的最小间距
        layout.minimumLineSpacing = 30;
        //设置header的尺寸
        layout.headerReferenceSize = CGSizeMake(100, 60);
        //设置footer的尺寸
        layout.footerReferenceSize = CGSizeMake(200, 60);
        
        _classification = [[UICollectionView alloc]initWithFrame:CRM(0, 128, SCREEN_WIDTH, 300 *PROPORTION_H) collectionViewLayout:layout];
        [_classification registerClass:[ClassCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        _classification.dataSource = self;
        _classification.delegate = self;
        _classification.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
        _classification.backgroundColor = [UIColor whiteColor];
        self.automaticallyAdjustsScrollViewInsets = NO;
//        _classification.
    }

    return _classification;
}
- (HeaderLabelView *)headerView{
    if (!_headerView) {
        _headerView = [[HeaderLabelView alloc]initWithFrame:CRM(0*PROPORTION_W, 64 *PROPORTION_H, SCREEN_WIDTH, 64*PROPORTION_H)];
        _headerView.messageSize = [self getSizeWithMessage:[_dataSource allKeys][2]];
        _headerView.classNameLabel.text = [_dataSource allKeys][2];
        [_headerView.logoImg setImage:[UIImage imageNamed:@"酒水4"]];
    }


    return _headerView;
}
- (YJCalenderView *)canlenderView{
    if (!_canlenderView) {
        _canlenderView = [[YJCalenderView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT + 320 *PROPORTION_H, SCREEN_WIDTH, 320*PROPORTION_H)];
        [_canlenderView.deleteButton addTarget:self action:@selector(deleteButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
        _canlenderView.backgroundColor = [UIColor whiteColor];
        [_canlenderView.soureButton addTarget:self action:@selector(soureButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
        
//        _canlenderView.hidden = YES;
    }
    
    return _canlenderView;
}
- (UIView *)keyBord{
    if (!_keyBord) {
        _keyBord = [[UIView alloc]initWithFrame:CRM(0, 420 *PROPORTION_H, SCREEN_WIDTH, SCREEN_HEIGHT - 420 *PROPORTION_H)];
        _keyBord.backgroundColor = [UIColor cyanColor];
        UIButton *dateButton = [UIButton buttonWithType:UIButtonTypeSystem];
        dateButton.frame = CRM(60 *PROPORTION_W, 10 *PROPORTION_H, 70*PROPORTION_W, 20 *PROPORTION_H);
        dateButton.tintColor = [UIColor blueColor];
        dateButton.layer.cornerRadius = 6*PROPORTION_H;
        dateButton.layer.borderWidth = 2;
        [dateButton addTarget:self action:@selector(dateButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
        dateButton.layer.borderColor = [UIColor redColor].CGColor;
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat =@"MM月dd日";
        NSDateFormatter *formatter2 = [[NSDateFormatter alloc]init];
        formatter2.dateFormat =@"MM";
        _str = (NSMutableString *)[formatter2 stringFromDate:date];
        NSDateFormatter *formatter3 = [[NSDateFormatter alloc]init];
        formatter3.dateFormat =@"dd";
        _keyStr = (NSMutableString *)[formatter3 stringFromDate:date];
        dateButton.tag = 12;
        NSString *string = [formatter stringFromDate:date];
        [dateButton setTitle:string forState:UIControlStateNormal];
        [_keyBord addSubview:dateButton];
        
        UIButton *beiButton = [UIButton buttonWithType:UIButtonTypeCustom];
        beiButton.frame = CRM(SCREEN_WIDTH - 105 *PROPORTION_W, 10 *PROPORTION_H, 24*PROPORTION_W, 20 *PROPORTION_H);
        [beiButton setImage:[UIImage imageNamed:@"备注"] forState:UIControlStateNormal];
        [_keyBord addSubview:beiButton];
        int j = -1;
        NSArray *arr = @[@"7",@"8",@"9",@"10",@"4",@"5",@"6",@"00",@"1",@"2",@"3",@"确定",@"C",@"0",@"."];
        for (int i = 0; i < 15; i ++) {
            if (i%4 == 0) {
                j ++;
            }
            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            [button setTitle:arr[i] forState:UIControlStateNormal];
            button.backgroundColor = [UIColor whiteColor];
            button.frame = CRM( 5 +BUTTON_WIDTH*(i % 4),40 + BUTTON_HEIGHT * (j % 4), BUTTON_WIDTH - 5, BUTTON_HEIGHT-3);
            if (i == 11) {
                button.frame = CRM( 5 +BUTTON_WIDTH*(i % 4),0 + BUTTON_HEIGHT * (j % 4) + 40, BUTTON_WIDTH - 5, BUTTON_HEIGHT * 2 - 4);
            }
            if (i == 3) {
                [button setImage:[UIImage imageNamed:@"回删"] forState:UIControlStateNormal];
                [button setTitle:@"" forState:UIControlStateNormal];
            }
            [button addTarget:self action:@selector(buttonTaped:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = 10 +i;
            [_keyBord addSubview:button];
        }

    }
    return _keyBord;
}

#pragma mark -- 点击事件
- (void)buttonTaped:(UIButton *)sender{
    
    switch (sender.tag) {
        case 13:
        {
            if ([_backStr isEqualToString:@"00"]) {
                _beforeStr= (NSMutableString *) [_beforeStr substringToIndex:_beforeStr.length - 1];
                if (_beforeStr.length == 0) {
                    _beforeStr = [NSMutableString stringWithFormat:@"0"];
                    _flag1 = NO;
                    _flag = NO;
                    _zeroFlag = NO;
                }
            }else{
                if (![_backStr hasSuffix:@"0"]) {
                     [_backStr replaceCharactersInRange:NSMakeRange(1, 1) withString:@"0"];
                    _flag1 = YES;
                    _flag = NO;
                    _zeroFlag = NO;
                }
                else{
                
                [_backStr replaceCharactersInRange:NSMakeRange(0, 1) withString:@"0"];
                
                }
            }
            
        }
            break;
        case 21:
        {
            [self biloddingPilst];

            [self dismissViewControllerAnimated:YES completion:nil];
        }
            break;
        case 22:
        {
            _headerView.moneyLabel.text = @"0.00";
            _flag1 = NO;
            _flag = NO;
            _zeroFlag = NO;
            _beforeStr = [NSMutableString stringWithFormat:@"0"];
            _backStr = [NSMutableString stringWithFormat:@"00"];
        }
            break;
        case 24:
        {
           _flag1 = YES;
            
        }
            break;
        default:
            
        {
            if (_flag1 ) {
                
                if ([sender.titleLabel.text isEqualToString:@"00"]) {
                    break;
                }
                
                if (!_flag) {
                    
                if ([_backStr isEqualToString:@"00"] && !_zeroFlag) {
                   [_backStr replaceCharactersInRange:NSMakeRange(0, 1) withString:[NSString stringWithFormat:@"%ld",[sender.titleLabel.text integerValue]]];
                    _zeroFlag = YES;
                }
                else{
                [_backStr replaceCharactersInRange:NSMakeRange(1, 1) withString:[NSString stringWithFormat:@"%ld",[sender.titleLabel.text integerValue]]];
                    _flag = YES;
                }
                }
            }
            else{
                               if ([_beforeStr integerValue] == 0) {
                    _beforeStr = (NSMutableString *)sender.titleLabel.text;
                    if ([_beforeStr isEqualToString:@"00"]) {
                        _beforeStr = [NSMutableString stringWithFormat:@"0"];
                    }
                }
                else{
               _beforeStr = (NSMutableString *)[_beforeStr stringByAppendingString:[NSString stringWithFormat:@"%@",sender.titleLabel.text]];
                
                }
                }
            
            
        }
            break;
    }
    if (_beforeStr.length > 6) {
       _beforeStr= (NSMutableString *) [_beforeStr substringToIndex:6];
    }
    NSString *str = [NSString stringWithFormat:@"%@.%@",_beforeStr,_backStr];
    _headerView.moneyLabel.text = str;
}

- (void)deleteButtonTaped:(UIButton *)sender{
//self.canlenderView.hidden = YES;
    [self resboderKeyBord];
    
    [self.canlenderView.collectionView reloadData];
    Changed *changed = [Changed defaultSingleton];
    [changed.dic removeAllObjects];
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat =@"yyyy--MM--dd";
    NSString *string = [formatter stringFromDate:date];
    self.canlenderView.dateLabel.text = string;
    NSDate *date1 = [NSDate date];

    UIButton *button = [self.view viewWithTag:12];
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc]init];
    formatter1.dateFormat =@"MM月dd日";
    NSString *string1 = [formatter1 stringFromDate:date1];
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc]init];
    formatter2.dateFormat =@"MM";
    _str = (NSMutableString *)[formatter2 stringFromDate:date1];
    NSDateFormatter *formatter3 = [[NSDateFormatter alloc]init];
    formatter3.dateFormat =@"dd";
    _keyStr = (NSMutableString *)[formatter3 stringFromDate:date1];
    [button setTitle:string1 forState:UIControlStateNormal];
    
}
- (void)soureButtonTaped:(UIButton *)sender{
//    self.canlenderView.hidden = YES;
    [self resboderKeyBord];
    UIButton *button = [self.view viewWithTag:12];
    NSDate *date = self.canlenderView.chooseDate;
    if (date == nil) {
        date = [NSDate date];
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat =@"MM月dd日";
    NSDateFormatter *formatter2 = [[NSDateFormatter alloc]init];
    formatter2.dateFormat =@"MM";
    _str = (NSMutableString *)[formatter2 stringFromDate:date];
    NSDateFormatter *formatter3 = [[NSDateFormatter alloc]init];
    formatter3.dateFormat =@"dd";
    _keyStr = (NSMutableString *)[formatter3 stringFromDate:date];
    NSString *string = [formatter stringFromDate:date];
    [button setTitle:string forState:UIControlStateNormal];

}
- (void)dateButtonTaped:(UIButton *)sender{
    self.canlenderView.chooseDate = nil;
    self.canlenderView.date = [NSDate date];
    [self.canlenderView.collectionView reloadData];
//   self.canlenderView.hidden = NO;
    [self keyBordAnimation];
}

#pragma mark -- 动画
//Cell动画
- (void)cellAnimationView:(UIView *)animationView{
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:animationView.center];
    [path addQuadCurveToPoint:CPM(CGRectGetMidX(self.headerView.logoImg.frame) + 0, CGRectGetMidY(self.headerView.logoImg.frame) + 76*PROPORTION_H)  controlPoint:CPM(SCREEN_WIDTH/2 , 100)];
    CAKeyframeAnimation *moveAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    moveAnimation.duration = 0.5 ;
        moveAnimation.path = path.CGPath; //贝塞尔
        moveAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; //淡入淡出
    moveAnimation.fillMode = kCAFillModeForwards;  //填充状态,back 是开始动画前的位置，forward是动画结束以后的状态
        moveAnimation.removedOnCompletion = NO;//是否移除动画
    
    [animationView.layer addAnimation:moveAnimation forKey:nil];
    
}
//键盘动画
- (void)keyBordAnimation{

    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        //在动画块里改变视图的可见属性
        _canlenderView.frame = CGRectMake(0, SCREEN_HEIGHT - 320 *PROPORTION_H, SCREEN_WIDTH, 320*PROPORTION_H);
        
    } completion:^(BOOL finished) {
            }];

}
- (void)resboderKeyBord{
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        //在动画块里改变视图的可见属性
        _canlenderView.frame = CGRectMake(0, SCREEN_HEIGHT + 320 *PROPORTION_H, 0, 0*PROPORTION_H);
    } completion:^(BOOL finished) {
    }];
    
}
/**
 *  根据日期创建plist文件
 */

- (void)biloddingPilst{
//    一月：January
//    
//    二月：February
//    
//    三月：March
//    
//    四月：April
//    
//    五月：May
//    
//    六月：June
//    
//    七月：July
//    
//    八月：August
//    
//    九月：September 
//    
//    十月：October 
//    
//    十一月：November
//    
//    十二月：December
    
    NSDictionary *dic = @{@"01":@"January.plist",@"02":@"February.plist",@"03":@"March.plist",@"04":@"April.plist",@"05":@"May.plist",@"06":@"June.plist",@"07":@"July.plist",@"08":@"August.plist",@"09":@"September.plist",@"10":@"October.plist",@"11":@"November.plist",@"12":@"December.plist"};
    
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@",path);
    //获取完整路径
    NSString *documentsPath = [path objectAtIndex:0];
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:dic[_str]];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
    NSMutableDictionary *mayDic = [NSMutableDictionary dictionaryWithDictionary:dict];
    _dic = [NSMutableDictionary dictionaryWithDictionary:mayDic[_keyStr]];
    if (![_headerView.moneyLabel.text isEqualToString:@"0.00"]) {
        [_dic setObject:_headerView.moneyLabel.text forKey:_headerView.classNameLabel.text];
    }
    
    [mayDic setObject:_dic forKey:_keyStr];
    [mayDic writeToFile:plistPath atomically:YES];

}


@end
